import 'dart:convert';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_niandaxue/component/base_components.dart';
import 'package:flutter_niandaxue/config/index.dart';
import 'package:flutter_niandaxue/model/base_model.dart';
import 'package:flutter_niandaxue/service/http_service.dart';

import 'exam_paper_question.dart';

/*
 * 用途: 试卷视图组件
 * 日期：2020-02-26
 */
class ExamPaperPage extends StatefulWidget{
  Course course; // 课程信息
  int examPaperFlag;// 试卷标识
  ExamPaperPage({Key key,@required this.course, @required this.examPaperFlag}):super(key:key);

  @override
  State<StatefulWidget> createState() => new _ExamPaperPageState(course: this.course, examPaperFlag: this.examPaperFlag, key:this.key);
}

class _ExamPaperPageState extends State<ExamPaperPage> with AutomaticKeepAliveClientMixin, SingleTickerProviderStateMixin   {
  Course course;
  int examPaperFlag;
  Key key;
  _ExamPaperPageState({this.course, this.examPaperFlag, this.key});

  int _currentPage = 1;
  int _totalPage = 1;
  int _total = 0;
  List _examPaperList = [];
  bool _dataLoadFlag = false;
  String _loadMoreText = KString.notMoreData;
  TextStyle _loadMoreTextStyle = KFont.notFoundData;
  final ScrollController _examPaperController = new ScrollController();

  @override
  void initState() {
    // 1 加载表单数据
    _initLoadData();
    // 2 初始化滚动监听器，加载更多使用
    _examPaperController.addListener(() {
      if (_examPaperController.position.pixels == _examPaperController.position.maxScrollExtent) {
        _loadMoreData(true);
      }
    });
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    String title =  course.name + KString.examPaperTitle;
    return Scaffold(
      appBar: AppBar(
        title: Text(title),
      ),
      body: Center(
        child: Container(
          child: RefreshIndicator(
              onRefresh: _onRefresh,
              child: _buildBody()
          ),
        ),
      ),
    );
  }
  // 构建Body
  Widget _buildBody() {
    if (!_dataLoadFlag) {
      return Center(
        child: Text('加载中...'),
      );
    } else {
      if(_examPaperList.length == 0){
        return NothingListView();
      }
      // 2 构建视图列表
      ListView listView = ListView.builder(
        itemBuilder: _buildListView,
        itemCount: _examPaperList.length + 1,
//        controller: _examPaperController,
      );
      return listView;
    }
  }

  // 延迟2秒后添加新数据， 模拟网络加载
  Future<Null>  _onRefresh() async {
    await Future.delayed(Duration(seconds: 2), () {
      setState(() {
        _initLoadData();
      });
    });
  }

  // 构建单条数据信息
  Widget _buildListView(context, index){
    // 1 第一行提示信息
    if(index == 0){
      return _tiShiXinXi();
    }
    // 2 最下面一行
    if (index == this._examPaperList.length+1) {
      return this._buildProgressMoreIndicator();
    }
    // 3 中间显示内容
    ExamPaper examPaper = ExamPaper.fromJson(_examPaperList[index-1]);
    return Container(
      padding: const EdgeInsets.symmetric(vertical: 2.0, horizontal: 2.0),
      margin: const EdgeInsets.only(bottom: 2.0),
      decoration: BoxDecoration(
        color: Colors.white,
        boxShadow: [
          new BoxShadow(
            color: const Color(0xFFd0d0d0),
            blurRadius: 1.0,
            spreadRadius: 2.0,
            offset: Offset(3.0, 2.0),
          ),
        ],
      ),
      child: ListTile(
//        selected: true,
        leading: Image.asset(KImage.examPaper, height: 100),
        title: Text(
          examPaper.smallName,
          overflow: TextOverflow.ellipsis,
          style:  KFont.courseTitleStyle,
        ),
        subtitle:Text(examPaper.examPaperName,
          style: KFont.courseSubTitleStyle,
        ),
        trailing: Icon(Icons.keyboard_arrow_right, color: Colors.grey, size: 40.0),
        onTap: () {
          Navigator.push(context, MaterialPageRoute(
              builder:(context){
                return ExamPaperQuestionPage(course:course, examPaper:examPaper, isAddStudyFlag: false,);
              }
          ));
        },
      ),
    );
  }


  // 提示信息
  Widget _tiShiXinXi() {
    String message = "试卷共 " + _total.toString() + "套";
    return Container(
      height: 30.0,
      padding: const EdgeInsets.only(left: 10.0),
      child: Row(
        children: <Widget>[
          Icon(Icons.book, size: 20.0,),
          Expanded(
            child: Container(
              margin: EdgeInsets.only(left: 10),
              child: Text(message,
                style: new TextStyle(
                  color: Colors.green, //字体颜色
                  fontSize: 15.0,
                  height: 1.5,
                  letterSpacing: 1.0, //字体间距
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }

  // 上拉加载数据
  _loadMoreData(bool flag) async {
    if(_totalPage <= _currentPage && _totalPage > 0){
    }else{
      if(flag){
        setState(() {
          _currentPage ++ ;
          _getExamPaperList();
        });
      }else{
        await Future.delayed(Duration(seconds: 1), () {
          setState(() {
            _currentPage ++ ;
            _getExamPaperList();
          });
        });
      }
    }
  }

  // 加载更多进度条
  Widget _buildProgressMoreIndicator() {
    return new Padding(
      padding: const EdgeInsets.all(15.0),
      child: new Center(
        child: new Text(_loadMoreText, style: KFont.loading),
      ),
    );
  }

  // 初始化数据
  _initLoadData(){
    _examPaperList.clear();
    _dataLoadFlag = false;
    _currentPage = 1;
    _totalPage = 1;
    _total = 0;
    _getExamPaperList();
  }

  _getExamPaperList() async {
    var formPage = {'page':{'current':_currentPage ,'size':KLength.pageSize},'courseCode':course.code, 'examPaperFlag':examPaperFlag};
    request_post_json('examPaper/listPage', formData:formPage).then((val){
      var data = json.decode(val.toString());
      Page page = Page.fromJson(data['data']);
      setState(() {
        _examPaperList.addAll(page.records) ;
        _totalPage = page.pages;
        _total = page.total;
        _currentPage = page.current;
        if(_currentPage == _totalPage){
          _loadMoreText = KString.notMoreData;
        }
        _dataLoadFlag = true;
      });
    });
  }

  MovieListState({Key key}) {
    // 固定写法，初始化滚动监听器，加载更多使用
    _examPaperController.addListener(() {
      var maxScroll = _examPaperController.position.maxScrollExtent;
      var pixel = _examPaperController.position.pixels;
      if (maxScroll == pixel && _totalPage > _currentPage && _totalPage > 0) {
        setState(() {
          _loadMoreText = KString.loading;
          _loadMoreTextStyle = KFont.loading;
        });
        _loadMoreData(false);
      } else {
        setState(() {
          _loadMoreText = KString.notMoreData;
          _loadMoreTextStyle = KFont.notFoundData;
        });
      }
    });
  }

  @override
  void dispose() {
    _examPaperController.dispose();
    super.dispose();
  }

  @override
  // TODO: implement wantKeepAlive
  bool get wantKeepAlive => true;
}



